package org.goldenport.g3.messages.http

import scala.xml._
import javax.servlet.http.HttpServletResponse
import com.asamioffice.goldenport.text.Strings
import org.goldenport.g3.{G3Message, G3TextMimeTyped}
import org.goldenport.g3.messages.html.Css

/**
 * @since   Nov. 28, 2010
 * @version Dec. 10, 2010
 * @author  ASAMI, Tomoharu
 */
class EventStream(val entries: List[EventStreamEntry],
                  val retry: Option[Long] = None) extends G3Message with G3TextMimeTyped {
  override def mimetype = Strings.mimetype.text_event_stream

  override def toText = {
    def retry_entry: Option[String] = {
      retry.map("retry: " + _.toString + "\n")
    }

    def event_entry_list: List[String] = {
      def event_entry(entry: EventStreamEntry): String = {
        def entry_event: List[String] = entry.event.map("event: " + _).toList
        def entry_id: List[String] = entry.id.map("id: " + _).toList
        def entry_data: List[String] = entry.data.map("data: " + _)
        List(entry_event, entry_id, entry_data).flatten.mkString("\n")
      }
      entries.map(event_entry)
    }

    (retry_entry.toList ::: event_entry_list).mkString("\n")
  }
}

object EventStream {
  def apply(data: String) = new EventStream(List(EventStreamEntry(List(data))))
  def apply(data: String, retry: Long) = new EventStream(List(EventStreamEntry(List(data))), Some(retry))
}

case class EventStreamEntry(
  data: List[String],
  id: Option[String] = None,
  event: Option[String] = None)
